package com.atguigu.boot.controller;

import com.atguigu.boot.entity.User;
import com.atguigu.boot.service.UserService;
import com.atguigu.boot.utils.Result;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 保存用户信息
     * @param user
     * @return
     */
    @PostMapping
    public Result save(@RequestBody User user) {
        userService.save(user);
        return Result.success();
    }

    /**
     * 删除用户信息
     * @param id 用户id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        userService.removeById(id);
        return Result.success();
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        userService.updateById(user);
        return Result.success();
    }

    /**
     * 根据用户id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        User user = userService.findById(id);
        return Result.success(user);
    }

    /**
     * 查询所有用户信息
     * @return
     */
    @GetMapping
    public Result<List<User>> findAll() {
        List<User> list = userService.list();
        return Result.success(list);
    }

    /**
     * 分页查询用户信息
     * @param pageNum 当前页码
     * @param pageSize 每页显示记录条数
     * @return
     */
    @GetMapping("/page")
    public Result<Page<User>> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "5") Integer pageSize) {
        Page<User> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        Page<User> userPage = userService.page(page);
        return Result.success(userPage);
    }

}
